package controller;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import util.DateJsonValueProcessor;

import com.zxf.pojo.Filesup;
import com.zxf.pojo.Params;
import com.zxf.pojo.Staff;
import com.zxf.pojo.StaffVo;
import com.zxf.service.FileService;

@Controller
@RequestMapping("filesup")
public class FileContorller {
	@Autowired
	private FileService fileService;
	private static Logger logger = Logger.getLogger(FileContorller.class);

	@ResponseBody
	@RequestMapping(value = "/photoUpload.do", method = RequestMethod.POST)
	public void addFileUp(StaffVo staffVo, 
			HttpServletResponse response, HttpServletRequest request){
		UUID uuid = UUID.randomUUID();
		Map<String, Object> map = new HashMap<String, Object>();
		Filesup fileUp = new Filesup();
		// 获取用户
		// Admin admin = (Admin) request.getSession().getAttribute("admin");
		// String id = request.getAttribute("id").toString();
		// String foo = request.getAttribute("foo").toString();
		// filesUp.getFile();
		// if(!filesUp.getFile().isEmpty()){
		// filesUp.getFile().transferTo(new
		// File("E:/upload/"+filesUp.getFile().getOriginalFilename()));
		// }
		// String photoname = request.getAttribute("photo").toString();
		int userid = 1;// 用户ID
		Date createdTime = new Date();
		// 使用MultipartHttpServletRequest包装文件数据
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 目录命名格式如：*files2013-03-05-22
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		dateformat.format(createdTime);
		// 构建图片保存的目录
		String foldername = "file" + dateformat.format(new Date());
		String logoPathDir = "E:/upload/" + foldername;
		// 得到图片保存目录的真实路径
		String logoRealPathDir = logoPathDir;
		// request.getSession().getServletContext().getRealPath(logoPathDir);
		// 根据真实路径创建目录
		File logoSaveFile = new File(logoRealPathDir);
		if (!logoSaveFile.exists())
			logoSaveFile.mkdirs();
		// 页面控件的文件流
		MultipartFile multipartFile = multipartRequest.getFile("avatar");
		if (null == multipartFile || "".equals(multipartFile)
				|| multipartFile.isEmpty()) {
			multipartFile = multipartRequest.getFile("imgFile");
		}
		// 获取文件名/
		String filename = multipartFile.getOriginalFilename();
		float filesize = multipartFile.getSize();
		// double filesize3= filesize
		float filesize2 = (filesize / 1024);
		String strfilesize = String.valueOf((float)(Math.round(filesize2*100))/100) + "KB";
		String filetype = multipartFile.getContentType();
		String filesrc = "http://127.0.0.1:8081/dpslogs/" + foldername + "/"
				+ filename;
		fileUp.setFilesize(strfilesize);
		fileUp.setFiletype(filetype);
		fileUp.setId(String.valueOf(uuid));
		fileUp.setFilename(filename);
		fileUp.setPath(logoPathDir);
		fileUp.setUpdata(dateformat.format(createdTime));
		fileUp.setFilesrc(filesrc);

		staffVo.setSraffid(String.valueOf(uuid));
		staffVo.setStaffno(fileUp.getId());
		long time = createdTime.getTime(); // 时间
		int index = filename.lastIndexOf(".");
		if (index == -1) {
			filename = filename + "-" + time; // 文件名
			logger.info("文件名：" + filename);
		} else {
			filename = filename.substring(0, index) + "-" + time
					+ filename.substring(index);
			logger.info("文件名：" + filename);
		}

		// 设置属性值
		// fileUp.setUserid(userid);
		// fileUp.setFilename(filename);
		// fileUp.setPath(logoRealPathDir);
		// fileUp.setStatue(1);
		// 拼成完整的文件保存路径加文件
		String fileName = logoRealPathDir + File.separator + filename;
		File file = new File(fileName);
		try {
			// 保存上传文件
			multipartFile.transferTo(file);
			logger.info(filename + "上传成功！！！");
			try {
				// 插入数据库
				int aa = fileService.insertFile(fileUp);
				if (aa > 0) {
					fileService.insertStaffVo(staffVo);
				}
				map.put("success", "true");
			} catch (Exception e) {
				// TODO: handle exception
				map.put("success", "false");
				logger.error("异常出现：" + e);
			}
			/*
			 * String json = "{success: true}";
			 * response.setContentType("text/html; charset=UTF-8");
			 * response.getWriter().write(json); response.flushBuffer();
			 */
			/*
			 * Map<String, Object> result = new HashMap<String, Object>(0);
			 * result.put("success", true);
			 * response.setContentType("text/html"); ObjectMapper mapper = new
			 * ObjectMapper(); mapper.writeValue(response.getOutputStream(),
			 * result);
			 */
			// render(new JsonRender(map).forIE());
			// renderJson();
//			if (!localUrl.equals("")) {
//				response.setContentType("text/html;charset=UTF-8");
//				response.getWriter().write("{error:0}");
//				return;
//			}
			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().write("{success:true}");
		} catch (IllegalStateException e) {
			logger.error("异常出现：" + e);
		} catch (IOException e) {
			logger.error("异常出现：" + e);
		}
		// response.setContentType("text/html; charset=UTF-8");
		// response.setContentType("application/json; charset=utf-8");
		// return new ModelAndView("jsonView", map);
		/*
		 * String json="{success : true}"; HttpHeaders reHeaders=new
		 * HttpHeaders(); reHeaders.setContentType(MediaType.TEXT_HTML); return
		 * new ResponseEntity<String>(json,reHeaders,HttpStatus.OK);
		 */

	}

	// 返回的map，会自动封装成json
	Map outmap = new HashMap();

	@Autowired
	private FileService staffService;

	@RequestMapping("/add")
	@ResponseBody
	public Map add(StaffVo staffVo, HttpServletRequest request,
			HttpServletResponse response) {
		// 持久层对象
		Staff staff = new Staff();
		/**
		 * 基本信息的提取 因为都是string类型，所有不可能为空， 持久层对象属性同是string类型的，不用进行判断，
		 * 非string类型的要进行判断，防止异常 extjs界面如果有格式限制的话，就不用trim处理，因为不允许输入空格
		 * 没有限制的话还是要进行trim处理的 对null进行trim处理会出现空指针异常，但幸亏传过来的值是空值""
		 */
		String staffname2 = (String) request.getAttribute("staffVo.staffname");
		String staffname = staffVo.getStaffname().trim();

		String staffmobile = staffVo.getStaffmobile();

		// 地址，进行拼接
		String staffcounty = staffVo.getStaffcounty();
		String staffpartaddress = staffVo.getStaffpartaddress().trim();

		// 非string类型，要进行判断
		String staffsalary = staffVo.getStaffsalary();
		if (!"".equals(staffsalary)) {
			double salary = Double.valueOf(staffsalary);
			staff.setStsalary(salary);
		}
		// 后加的工号 年份月份加序号（位数不够前面加0）
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int staffnum = staffService.getrecordSize();
		String staffnumstr = String.valueOf(staffnum);
		String[] ss = { "00000", "0000", "000", "00", "0", "" };
		staffnumstr = ss[staffnumstr.length() - 1] + staffnumstr;
		String stjobnumber = year + "" + month + staffnumstr;
		/**
		 * 填充到持久层对象中
		 */
		staff.setStname(staffname);
		staff.setStjobnumber(stjobnumber);
		/**
		 * 对上传文件进行处理
		 */
		// 获取servlet上下文
		ServletContext servletContext = request.getSession()
				.getServletContext();
		// spring的文件处理解析类，包装了servlet的上下文。
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				servletContext);
		// 是否有上传文件
		boolean hasUploadAvatar = false;
		// 如果是multipart的提交，这个判断有点多余，不过还是加上吧！
		if (multipartResolver.isMultipart(request)) {
			// 把request请求进行升级，request有的，它都有，
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			/**
			 * String staffname = multiRequest.getParameter("staffname");
			 * 这样也可以获得上面从staffVo里面取出的值
			 */
			// 获得上传文件的名称
			Iterator iter = multiRequest.getFileNames();
			// 如果有的话就依次取出来
			while (iter.hasNext()) {
				// 包装过的文件流
				MultipartFile file = multiRequest.getFile((String) iter.next());
				// 这里要进行判断，即使是空值，没有上传内容，file都是有值（空值）的，而文件流大小要大于0才是有上传的东西
				if (file.getSize() > 0) {
					// 获得上传文件原始名
					String imagename = file.getOriginalFilename();
					// 算出后缀名
					String ext = imagename
							.substring(imagename.lastIndexOf("."));
					// 对文件类型进行判断，这个操作也可以在前台进行处理，在前台进行处理比较好，前后台都进行处理最稳妥
					List fileTypes = new ArrayList();
					fileTypes.add(".jpg");
					fileTypes.add(".jpeg");
					fileTypes.add(".bmp");
					fileTypes.add(".gif");
					fileTypes.add(".png");
					// 是图片再进行处理
					if (fileTypes.contains(ext.toLowerCase())) {
						// 文件名为：唯一的工号 + avatar + 系统时间 + 后缀
						String fileName = stjobnumber + "avatar"
								+ System.currentTimeMillis() + ext;
						// 文件夹;String imagepath =
						// request.getRealPath("/upload");过时的方法，用request.getSession().getServletContext()代替
						String avatarFolder = servletContext
								.getRealPath("/upload");
						File localFile = new File(avatarFolder, fileName);
						try {
							// 直接写入到后台服务器，简单且快
							file.transferTo(localFile);
							staff.setStavatar(fileName);
							// 保存资料到数据库中
							staffService.insertSelective(staff);
							outmap.put("success", true);
							outmap.put("msg", "添加成功！");
							return outmap;
						} catch (IOException e) {
							e.printStackTrace();
							outmap.put("success", false);
							outmap.put("msg", "系统出错");
							return outmap;
						}
					} else {
						outmap.put("success", false);
						outmap.put("msg", "图片格式出错！");
						return outmap;
					}
				}
			}
		}
		if (!hasUploadAvatar) {
			staffService.insertSelective(staff);
			outmap.put("success", true);
			outmap.put("msg", "添加成功！");
			return outmap;
		}
		return null;
	}

	@ResponseBody
	@RequestMapping(value = "/swfUpload.do", method = RequestMethod.POST)
	public void swfFileUp(Filesup filesup, HttpServletResponse response,
			HttpServletRequest request) {
		UUID uuid = UUID.randomUUID();
		Map<String, Object> map = new HashMap<String, Object>();
		Filesup fileUp = new Filesup();
		// 接收参数 接收不到
		// String hello = request.getParameter("staffname");
		// String hellos = (String) request.getAttribute("staffname");
		int userid = 1;// 用户ID
		Date createdTime = new Date();
		// 使用MultipartHttpServletRequest包装文件数据
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 目录命名格式如：*files2013-03-05-22
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		// 构建图片保存的目录
		String foldername = "file" + dateformat.format(new Date());
		String logoPathDir = "E:/upload/file" + dateformat.format(new Date());
		// 得到图片保存目录的真实路径
		String logoRealPathDir = logoPathDir;
		// request.getSession().getServletContext().getRealPath(logoPathDir);
		// 根据真实路径创建目录
		File logoSaveFile = new File(logoRealPathDir);
		if (!logoSaveFile.exists())
			logoSaveFile.mkdirs();
		String filedName = "";
		// 页面控件的文件流
		// MultipartFile multipartFile = filesup.getFile();
		// 获取文件名/接收不到
		Iterator<String> filedFileNames = multipartRequest.getFileNames();

		while (filedFileNames.hasNext()) {
			filedName = filedFileNames.next(); // 文件文本框的名称
			// 获取该文件框中上传的文件，即对应到上传到服务器中的文件
		}
		MultipartFile multipartFile = multipartRequest.getFile(filedName);

		// fileUp.setFilename(filename);
		long time = createdTime.getTime(); // 时间
		int index = filedName.lastIndexOf(".");
		if (index == -1) {
			filedName = filedName + "-" + time; // 文件名
			logger.info("文件名：" + filedName);
		} else {
			filedName = filedName.substring(0, index) + "-" + time
					+ filedName.substring(index);
			logger.info("文件名：" + filedName);
		}

		// 设置属性值
		// fileUp.setUserid(userid);
		fileUp.setFilename(filedName);
		fileUp.setPath(logoRealPathDir);
		// fileUp.setStatue(1);
		// 拼成完整的文件保存路径加文件
		String fileName = logoRealPathDir + File.separator + filedName;
		File file = new File(fileName);
		// 获取文件名/
		String filename = multipartFile.getOriginalFilename();
		float filesize = multipartFile.getSize();
		// double filesize3= filesize
		float filesize2 = (filesize / 1024) ;
		String strfilesize = String.valueOf((float)(Math.round(filesize2*100))/100) + "KB";
		String filetype = multipartFile.getContentType();
		String filesrc = "http://127.0.0.1:8081/dpslogs/" + foldername + "/"
				+ filename;
		fileUp.setFilesize(strfilesize);
		fileUp.setFiletype(filetype);
		fileUp.setId(String.valueOf(uuid));
		fileUp.setFilename(filename);
		fileUp.setPath(logoPathDir);
		fileUp.setUpdata(dateformat.format(createdTime));
		fileUp.setFilesrc(filesrc);
		try {
			// 保存上传文件
			 multipartFile.transferTo(file);
			logger.info(filedName + "上传成功！！！");
			try {
				// 插入数据库
				int aa = fileService.insertFile(fileUp);
				map.put("success", "true");
			} catch (Exception e) {
				// TODO: handle exception
				map.put("success", "false");
				logger.error("异常出现：" + e);
			}

			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().write("{success:true}");
		} catch (IllegalStateException e) {
			logger.error("异常出现：" + e);
		} catch (IOException e) {
			logger.error("异常出现：" + e);
		}
		// response.setContentType("text/html; charset=UTF-8");
		// response.setContentType("application/json; charset=utf-8");
		// return new ModelAndView("jsonView", map);
		/*
		 * String json="{success : true}"; HttpHeaders reHeaders=new
		 * HttpHeaders(); reHeaders.setContentType(MediaType.TEXT_HTML); return
		 * new ResponseEntity<String>(json,reHeaders,HttpStatus.OK);
		 */

	}

	// 文件列表
	@RequestMapping(value = "/filelist.do", method = RequestMethod.POST)
	public @ResponseBody
	JSONObject filelist(Params params, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();

		JSONArray js = new JSONArray();
		// 页码
		int pageno = params.getPage();
		// 每页数量
		int pageSize2 = params.getLimit();
		// int start2 = (Integer.parseInt(pageno)-1)*Integer.parseInt(pageSize);
		int start = (params.getPage() - 1) * params.getLimit();
		params.setStart(start);
		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		// jsonConfig.registerJsonValueProcessor(Date.class, new
		// JsonDateValueProcessor());
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		List filelist = fileService.getFilelist(params);
		int totle = fileService.getFiletotle();
		obj.put("data", js.fromObject(filelist, jsonConfig));
		obj.put("total", totle); // 统计数量，
		obj.put("success", true);

		// /response.setHeader("Cache-Control", "no-cache");
		// response.setContentType("text/json;charset=utf-8");
		// response.getWriter().write(obj.toString());
		// TODO Auto-generated catch block
		// json格式化后输出
		System.out.println(obj.toString());
		return obj;

	}

	// kindeditor上传文件
	@ResponseBody
	@RequestMapping(value = "/kindeditorUpload.do", method = RequestMethod.POST)
	public JSONObject addkindeditorFileUp(StaffVo staffVo, String localUrl,
			HttpServletResponse response, HttpServletRequest request){
		UUID uuid = UUID.randomUUID();
		Filesup fileUp = new Filesup();
		JSONObject obj = new JSONObject();

		int userid = 1;// 用户ID
		Date createdTime = new Date();
		// 使用MultipartHttpServletRequest包装文件数据
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 目录命名格式如：*files2013-03-05-22
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		dateformat.format(createdTime);
		// 构建图片保存的目录
		String foldername = "file" + dateformat.format(new Date());
		String logoPathDir = "E:/upload/" + foldername;
		// 得到图片保存目录的真实路径
		String logoRealPathDir = logoPathDir;
		// 根据真实路径创建目录
		File logoSaveFile = new File(logoRealPathDir);
		if (!logoSaveFile.exists())
			logoSaveFile.mkdirs();
		// 页面控件的文件流
		MultipartFile multipartFile = multipartRequest.getFile("avatar");
		if (null == multipartFile || "".equals(multipartFile)
				|| multipartFile.isEmpty()) {
			multipartFile = multipartRequest.getFile("imgFile");
		}
		// 获取文件名/
		String filename = multipartFile.getOriginalFilename();
		float filesize = multipartFile.getSize();
		// double filesize3= filesize
		float filesize2 = (filesize / 1024) ;
		String strfilesize = String.valueOf((float)(Math.round(filesize2*100))/100) + "KB";
		String filetype = multipartFile.getContentType();
		String filesrc = "http://127.0.0.1:8081/dpslogs/" + foldername + "/"
				+ filename;
		fileUp.setFilesize(strfilesize);
		fileUp.setFiletype(filetype);
		fileUp.setId(String.valueOf(uuid));
		fileUp.setFilename(filename);
		fileUp.setPath(logoPathDir);
		fileUp.setUpdata(dateformat.format(createdTime));
		fileUp.setFilesrc(filesrc);

		staffVo.setSraffid(String.valueOf(uuid));
		staffVo.setStaffno(fileUp.getId());
		// 拼成完整的文件保存路径加文件
		String fileName = logoRealPathDir + File.separator + filename;
		File file = new File(fileName);
		try {
			// 保存上传文件
			multipartFile.transferTo(file);
			logger.info(filename + "上传成功！！！");
			try {
				// 插入数据库
				int aa = fileService.insertFile(fileUp);
				if (aa > 0) {
					fileService.insertStaffVo(staffVo);
				}
				obj.put("error", 0);
				obj.put("url", filesrc);
			} catch (Exception e) {
				// TODO: handle exception
				logger.error("异常出现：" + e);
			}

		} catch (IllegalStateException e) {
			logger.error("异常出现：" + e);
		} catch (IOException e) {
			logger.error("异常出现：" + e);
		}
		return obj;

	}
	

	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toString();
	}

}